package org.ligson.hbase127;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.hadoop.hbase.client.Connection;

import java.io.IOException;

public class HBaseConnectionFactory {
    private final GenericObjectPool<Connection> pool;
    private final HBasePoolFactory hBasePoolFactory;
    private final GenericObjectPoolConfig<Connection> poolConfig;

    public HBaseConnectionFactory(HBasePoolFactory hBasePoolFactory,
                                  GenericObjectPoolConfig<Connection> poolConfig) {
        this.hBasePoolFactory = hBasePoolFactory;
        this.poolConfig = poolConfig;
        pool = new GenericObjectPool<Connection>(hBasePoolFactory, poolConfig);
    }

    public Connection getConnection() throws Exception {
        return pool.borrowObject();
    }

    public void closeConnection(Connection connection) throws IOException {
        if (!connection.isClosed()) {
            connection.close();
        }
        pool.returnObject(connection);
    }
}
